<?php

namespace app\http\middleware;

use app\model\AdminOrderItem;
use app\util\Aes;
use app\util\ReturnCode;

class AppGetStoreByCode
{

    /**
     * 核销中请求中通过code来获取当前操作的店铺sid，并将code解码
     * @param \think\facade\Request $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle($request, \Closure $next)
    {
        $code = $request->param('code');
        if (!isset($code)) {
            return json([
                'code' => ReturnCode::FAILED,
                'msg' => '无效的参数',
                'data' => []
            ]);
        } else {
            $key = config('wechat.USE_CODE_KEY');
            $aes = new Aes($key);
            //这里要先对当前用户鉴权，验证当前用户是否是当前店铺的管理用户
            $orderItemId = $aes->decrypt($code);
            $orderItemModel = AdminOrderItem::get($orderItemId);
            if ($orderItemModel) {
                $sid = $orderItemModel->sid;
                $get =$request->get();
                $get['code']=$orderItemId;
                $get['sid']=$sid;
                //把参数传递到后面
                $request->withGet($get);
                //鉴权通过
                return $next($request);
            }
            return json([
                'code' => ReturnCode::FAILED,
                'msg' => '无效的参数',
                'data' => []
            ]);
        }
    }
}
